﻿using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using CommunityToolkit.Mvvm.Input;
using System;
using System.Collections; // Required for IList
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics; // 需要 Debug
using System.Linq;
using System.Windows;
using System.Windows.Controls;

using System.Windows.Input; // 需要 MouseEventArgs, DragEventArgs
using System.Windows.Media;
using Point = System.Windows.Point; // 需要 VisualTreeHelper

using System.Windows.Controls.Primitives;
using RevitProject.SpaceManager.ViewModel.SpaceViewModel;
using RevitProject.SpaceManager.ViewModel.RoomViewModelPart;
using RevitProject.SpaceManager.ViewModel;
using RevitProject.SpaceManager.ViewModel.HAVCLoadViewModelPart;
using System.ComponentModel; // Selector

namespace RevitProject.SpaceManager.Views
{
    public partial class SpaceManagerView : Window
    {
        private readonly SpaceManagerVm _viewModel;
        private Point _startPoint;
        private bool _isDragging = false;
        private readonly Dictionary<HVACLoadItemViewModel, PropertyChangedEventHandler> _hvacItemPropertyChangedHandlers =
    new Dictionary<HVACLoadItemViewModel, PropertyChangedEventHandler>();
        public SpaceManagerView(Document doc, UIApplication uiApp)
        {
            InitializeComponent();

            // 创建 ViewModel 实例并赋值给成员变量
            _viewModel = new SpaceManagerVm(this, doc, uiApp);

            // 将 DataContext 设置为已创建并赋值的 _viewModel
            this.DataContext = _viewModel; 

            
            Debug.WriteLine($"调试信息 - SpaceManagerView 构造函数: _viewModel 是否为 null? -> {_viewModel == null}");
            if (_viewModel != null)
            {
                Debug.WriteLine($"调试信息 - SpaceManagerView 构造函数: _viewModel.HAVCLoadVM 是否为 null? -> {_viewModel.HAVCLoadVM == null}");
            }


            // Loaded 事件处理器保持不变
            this.Loaded += async (sender, e) =>
            {
                Debug.WriteLine("SpaceManagerView 已加载。请求初始数据加载...");
                // 现在可以安全地使用 _viewModel
                if (_viewModel != null && _viewModel.LoadDataCommand.CanExecute(null))
                {
                    await _viewModel.LoadDataCommand.ExecuteAsync(null);
                }
            };

        }

        // --- Room DataGrid Drag Source ---
        private void RoomDataGrid_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e) 
        { /* ... existing code ... */ _startPoint = e.GetPosition(null); _isDragging = false; }
        private void RoomDataGrid_PreviewMouseMove(object sender, MouseEventArgs e) 
        { /* ... existing code ... */ if (e.LeftButton == MouseButtonState.Pressed && !_isDragging) { Point position = e.GetPosition(null); if (Math.Abs(position.X - _startPoint.X) > SystemParameters.MinimumHorizontalDragDistance || Math.Abs(position.Y - _startPoint.Y) > SystemParameters.MinimumVerticalDragDistance) { if (sender is DataGrid grid && grid.SelectedItems != null && grid.SelectedItems.Count > 0) { _isDragging = true; var selectedVMs = grid.SelectedItems.OfType<RoomViewModel>().ToList(); if (selectedVMs.Any()) { DataObject dragData = new DataObject("DraggedRoomViewModels", selectedVMs); Debug.WriteLine($"开始拖动 {selectedVMs.Count} 个房间..."); DragDrop.DoDragDrop(grid, dragData, DragDropEffects.Move); } _isDragging = false; } } } }

        // --- TreeView Drop Target (Category Tree) ---
        private void CategoryTreeView_DragOver(object sender, DragEventArgs e) { /* ... existing code ... */ e.Effects = DragDropEffects.None; if (e.Data.GetDataPresent("DraggedRoomViewModels")) { TreeViewItem targetItem = GetTreeViewItemUnderMouse(CategoryTreeViewControl, e.GetPosition(CategoryTreeViewControl)); if (targetItem != null && targetItem.DataContext is CategoryTreeNodeViewModel targetNode) { if (!targetNode.IsAllRoomsNode && !targetNode.DisplayName.Equals("其他类", StringComparison.OrdinalIgnoreCase) && targetNode.IsLeafNode) { e.Effects = DragDropEffects.Move; } } } e.Handled = true; }
        private void CategoryTreeView_Drop(object sender, DragEventArgs e)
        { 
            if (e.Data.GetDataPresent("DraggedRoomViewModels"))
            {
                var draggedRoomVMs = e.Data.GetData("DraggedRoomViewModels") as List<RoomViewModel>;
                TreeViewItem targetItem = GetTreeViewItemUnderMouse(CategoryTreeViewControl, e.GetPosition(CategoryTreeViewControl));
                CategoryTreeNodeViewModel targetNode = targetItem?.DataContext as CategoryTreeNodeViewModel; if (this.DataContext is SpaceManagerVm viewModel && draggedRoomVMs != null && targetNode != null) { if (!targetNode.IsAllRoomsNode && !targetNode.DisplayName.Equals("其他类", StringComparison.OrdinalIgnoreCase) && targetNode.IsLeafNode) { var parameter = new AssignCategoryParameter { TargetCategoryNode = targetNode, SelectedRoomVMs = draggedRoomVMs }; if (viewModel.DropRoomsOntoCategoryCommand.CanExecute(parameter)) { Debug.WriteLine($"准备将 {draggedRoomVMs.Count} 个房间放置到 '{targetNode.DisplayName}'..."); viewModel.DropRoomsOntoCategoryCommand.Execute(parameter); } else { Debug.WriteLine($"不能将房间放置到 '{targetNode.DisplayName}' (命令 CanExecute 返回 false)。"); } } else { Debug.WriteLine($"目标节点 '{targetNode.DisplayName}' 不是有效的放置目标。"); } } else { Debug.WriteLine("放置操作失败：无法获取 ViewModel、拖动数据或目标节点。"); }
            }
            else { Debug.WriteLine("放置操作失败：数据格式不正确。"); }
            e.Handled = true;
        }

        // --- Context Menu Click Handlers (Category Tree) ---
        private void AddChildCategory_Click(object sender, RoutedEventArgs e) { /* ... existing code ... */ if (sender is MenuItem menuItem && menuItem.DataContext is CategoryTreeNodeViewModel nodeViewModel && this.DataContext is SpaceManagerVm mainViewModel) { if (mainViewModel.AddChildCategoryCommand.CanExecute(nodeViewModel)) { Debug.WriteLine($"Code-behind: Executing AddChildCategory for node '{(nodeViewModel?.DisplayName ?? "<root context>")}'"); mainViewModel.AddChildCategoryCommand.Execute(nodeViewModel); } else { Debug.WriteLine($"Code-behind: Cannot execute AddChildCategory."); } } else { Debug.WriteLine($"Code-behind AddChildCategory_Click: Failed to get Menu Item, Node ViewModel, or Main ViewModel."); } }
        private void RenameCategory_Click(object sender, RoutedEventArgs e) { /* ... existing code ... */ if (sender is MenuItem menuItem && menuItem.DataContext is CategoryTreeNodeViewModel nodeViewModel && this.DataContext is SpaceManagerVm mainViewModel) { if (mainViewModel.RenameCategoryCommand.CanExecute(nodeViewModel)) { Debug.WriteLine($"Code-behind: Executing RenameCategory for node '{nodeViewModel.DisplayName}'"); mainViewModel.RenameCategoryCommand.Execute(nodeViewModel); } else { Debug.WriteLine($"Code-behind: Cannot execute RenameCategory for node '{nodeViewModel.DisplayName}'. CanExecute returned false."); } } else { Debug.WriteLine($"Code-behind RenameCategory_Click: Failed to get Menu Item, Node ViewModel, or Main ViewModel."); } }
        private void DeleteCategory_Click(object sender, RoutedEventArgs e) { /* ... existing code ... */ if (sender is MenuItem menuItem && menuItem.DataContext is CategoryTreeNodeViewModel nodeViewModel && this.DataContext is SpaceManagerVm mainViewModel) { if (mainViewModel.DeleteCategoryCommand.CanExecute(nodeViewModel)) { Debug.WriteLine($"Code-behind: Executing DeleteCategory for node '{nodeViewModel.DisplayName}'"); mainViewModel.DeleteCategoryCommand.Execute(nodeViewModel); } else { Debug.WriteLine($"Code-behind: Cannot execute DeleteCategory for node '{nodeViewModel.DisplayName}'. CanExecute returned false."); } } else { Debug.WriteLine($"Code-behind DeleteCategory_Click: Failed to get Menu Item, Node ViewModel, or Main ViewModel."); } }


        // --- Helper Method ---
        private TreeViewItem GetTreeViewItemUnderMouse(TreeView treeView, Point mousePosition)
        {
            if (treeView == null)
            {
                Debug.WriteLine("GetTreeViewItemUnderMouse ERROR: Passed TreeView is null!");
                return null;
            }
            var hitTestResult = VisualTreeHelper.HitTest(treeView, mousePosition);
            if (hitTestResult?.VisualHit is DependencyObject dependencyObject)
            {
                int loopCounter = 0;
                while (dependencyObject != null && !(dependencyObject is TreeViewItem) && loopCounter < 20)
                {

                    dependencyObject = VisualTreeHelper.GetParent(dependencyObject);
                    loopCounter++;
                }

                return dependencyObject as TreeViewItem;
            }

            return null;
        }


        private void SpaceDataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (sender is DataGrid grid && this.DataContext is SpaceManagerVm mainVm && mainVm.SpaceVM != null)
            {
                var spaceVmList = mainVm.SpaceVM.FilteredSpaceList;
                if (spaceVmList == null || !spaceVmList.Any())
                {
                    // 如果列表为空，确保全选框未选中
                    SetHeaderCheckBoxState(false);
                    return;
                }

                // --- 根据 VM 的 IsSelected 状态更新全选 CheckBox ---
                bool allSelected = spaceVmList.All(vm => vm.IsSelected);
                bool anySelected = spaceVmList.Any(vm => vm.IsSelected);

                if (allSelected)
                {
                    SetHeaderCheckBoxState(true); // 全部选中
                }
                else if (anySelected)
                {
                    SetHeaderCheckBoxState(null); // 部分选中 (中间态)
                }
                else
                {
                    SetHeaderCheckBoxState(false); // 全部未选中
                }
            }
        }

        // 辅助方法，用于设置全选 CheckBox 的状态 (包括中间态)
        private void SetHeaderCheckBoxState(bool? isChecked)
        {
            // 需要找到 Header 中的 CheckBox 控件
            // 这通常需要遍历可视化树或使用更可靠的方法
            var headerPresenter = FindVisualChild<DataGridColumnHeader>(SpaceDataGrid, 0); // 获取第一列的 Header
            if (headerPresenter != null)
            {
                // 在 HeaderPresenter 中查找名为 "HeaderCheckBox" 的 CheckBox
                var headerCheckBox = FindVisualChild<CheckBox>(headerPresenter, "HeaderCheckBox");
                if (headerCheckBox != null)
                {
                    headerCheckBox.IsChecked = isChecked;
                }
            }
        }

        // 辅助方法：在可视化树中查找子控件 (按类型)
        private static T FindVisualChild<T>(DependencyObject parent) where T : DependencyObject
        {
            if (parent == null) return null;
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
            {
                DependencyObject child = VisualTreeHelper.GetChild(parent, i);
                if (child != null && child is T)
                    return (T)child;
                else
                {
                    T childOfChild = FindVisualChild<T>(child);
                    if (childOfChild != null)
                        return childOfChild;
                }
            }
            return null;
        }
        // 辅助方法：在可视化树中查找子控件 (按类型和名称)
        private static T FindVisualChild<T>(DependencyObject parent, string name) where T : FrameworkElement // 改为 FrameworkElement 以访问 Name
        {
            if (parent == null) return null;
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
            {
                DependencyObject child = VisualTreeHelper.GetChild(parent, i);
                if (child is T element && element.Name == name) // 检查类型和名称
                    return element;
                else
                {
                    T childOfChild = FindVisualChild<T>(child, name); // 递归查找
                    if (childOfChild != null)
                        return childOfChild;
                }
            }
            return null;
        }
        // 辅助方法：获取指定列的 DataGridColumnHeader
        private static DataGridColumnHeader FindVisualChild<T>(DependencyObject parent, int columnIndex) where T : DataGridColumnHeader
        {
            var headersPresenter = FindVisualChild<DataGridColumnHeadersPresenter>(parent);
            if (headersPresenter != null && columnIndex < headersPresenter.Items.Count)
            {
                return headersPresenter.ItemContainerGenerator.ContainerFromIndex(columnIndex) as DataGridColumnHeader;
            }
            return null;
        }


        private void AssignSpaceTypeMenuItem_Click(object sender, RoutedEventArgs e)
        {
            if (sender is MenuItem menuItem &&
                menuItem.DataContext is SpaceTypeTreeNodeViewModel targetNode && // 获取右键点击的节点
                this.DataContext is SpaceManagerVm mainVm &&                     // 获取主 VM
                mainVm.SpaceVM != null &&                                        // 确保 SpaceVM 存在
                mainVm.SpaceVM.ChangeSpaceTypeCommand.CanExecute(null)) // 检查命令是否可执行（需要调整CanExecute以不依赖参数或传递所需信息）
            {
                // 1. 获取 DataGrid 中选中的 SpaceDisplayViewModel
                var selectedSpaceVMs = SpaceDataGrid.SelectedItems?.OfType<SpaceDisplayViewModel>().ToList();

                if (selectedSpaceVMs != null && selectedSpaceVMs.Any())
                {
                    // 2. 调用 SpaceTabViewModel 中的命令，传递选中的 VM 列表
                    //    注意：这里需要确保 ChangeSpaceTypeCommand 能接受 List<SpaceDisplayViewModel>
                    //    并且 CanExecute/Execute 逻辑在 ViewModel 内部能正确处理目标节点 (SelectedSpaceTypeNode)
                    if (mainVm.SpaceVM.ChangeSpaceTypeCommand is RelayCommand<List<SpaceDisplayViewModel>> cmd)
                    {
                        // 在调用 Execute 之前，确保 SpaceTabViewModel 中的 SelectedSpaceTypeNode
                        // 确实是用户右键点击的 targetNode。可以通过 UpdateSelectedSpaceTypeNodeCommand 实现。
                        if (mainVm.SpaceVM.UpdateSelectedSpaceTypeNodeCommand.CanExecute(targetNode))
                        {
                            mainVm.SpaceVM.UpdateSelectedSpaceTypeNodeCommand.Execute(targetNode);
                        }

                        // 现在可以检查 CanExecute 并执行
                        if (cmd.CanExecute(selectedSpaceVMs))
                        {
                            Debug.WriteLine($"Code-behind: Executing ChangeSpaceType for {selectedSpaceVMs.Count} spaces to target '{targetNode.DisplayName}'");
                            cmd.Execute(selectedSpaceVMs);
                        }
                        else
                        {
                            Debug.WriteLine($"Code-behind: Cannot execute ChangeSpaceType. CanExecute returned false for target '{targetNode.DisplayName}'.");
                        }
                    }
                    else
                    {
                        Debug.WriteLine($"Code-behind AssignSpaceTypeMenuItem_Click: ChangeSpaceTypeCommand is not of expected type RelayCommand<List<SpaceDisplayViewModel>>.");
                    }
                }
                else
                {
                    Debug.WriteLine("Code-behind AssignSpaceTypeMenuItem_Click: No spaces selected in the DataGrid.");
                    System.Windows.MessageBox.Show("请先在右侧表格中选择要归类的空间。", "提示", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Information);
                }
            }
            else
            {
                Debug.WriteLine($"Code-behind AssignSpaceTypeMenuItem_Click: Failed to get MenuItem, Target Node ViewModel, Main ViewModel, SpaceViewModel, or Command cannot execute.");
            }
        }



        private void ColumnSettingsButton_Click(object sender, RoutedEventArgs e)
        {
            // 1. 获取当前 DataGrid 的列信息 (Header, x:Name, Visibility)
            var currentColumnInfos = new List<ColumnVisibilityInfo>();
            foreach (var column in SpaceDataGrid.Columns)
            {

                string columnHeader = GetColumnName(column);
                if (!string.IsNullOrEmpty(columnHeader))
                {
                    currentColumnInfos.Add(new ColumnVisibilityInfo
                    {
                        Header = columnHeader,       // Header 和 ColumnName 都用 Header
                        ColumnName = columnHeader,
                        IsVisible = column.Visibility == System.Windows.Visibility.Visible
                    });
                }
            }

            // 2. 创建并显示对话框
            var dialog = new ColumnSelectionDialog(currentColumnInfos) { Owner = this };
            if (dialog.ShowDialog() == true)
            {
                // 3. 应用用户选择
                var selectedInfos = dialog.ColumnInfos; // 获取用户修改后的列表
                foreach (var info in selectedInfos)
                {
                    // 根据 ColumnName (x:Name) 找到对应的 DataGridColumn
                    DataGridColumn columnToUpdate = FindColumnByName(SpaceDataGrid, info.ColumnName);
                    if (columnToUpdate != null)
                    {
                        // 更新 Visibility
                        columnToUpdate.Visibility = info.IsVisible ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
                    }
                }
                Debug.WriteLine("用户列设置已应用。");
            }
            else
            {
                Debug.WriteLine("用户取消了列设置。");
            }


            if (_viewModel?.SpaceVM != null /* && _viewModel.SpaceVM.ShowColumnSettingsCommand.CanExecute(null) */)
            {
                
                MessageBox.Show("空间视图的列设置功能待实现。", "提示", MessageBoxButton.OK, MessageBoxImage.Information); // Placeholder
            }
            else
            {
                Debug.WriteLine("ColumnSettingsButton_Click (Space View): SpaceVM or command not available.");
            }

        }

        // 辅助方法：根据 DataGridColumn 获取其 x:Name (示例，可能需要调整)
        private string GetColumnName(DataGridColumn column)
        {
            return column.Header?.ToString();
        }

        // 辅助方法：根据 header查找 DataGridColumn
        private DataGridColumn FindColumnByName(DataGrid grid, string header)
        {
            if (string.IsNullOrEmpty(header) || grid == null) return null;

            foreach (var column in grid.Columns)
            {
                // 比较 Header 属性
                if (column.Header?.ToString().Equals(header, StringComparison.Ordinal) ?? false)
                {
                    return column;
                }
            }
            Debug.WriteLine($"警告：未能根据 Header '{header}' 找到对应的 DataGridColumn。");
            return null;
        }
        // ---  NEW: Space DataGrid Drag Source Handlers  ---
        private void SpaceDataGrid_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            // 与 RoomDataGrid_PreviewMouseLeftButtonDown 逻辑相同
            _startPoint = e.GetPosition(null);
            _isDragging = false;
            Debug.WriteLine("SpaceDataGrid MouseDown");
        }

        // SpaceManagerView.xaml.cs

        private void SpaceDataGrid_PreviewMouseMove(object sender, MouseEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed && !_isDragging)
            {
                Point position = e.GetPosition(null);
                if (Math.Abs(position.X - _startPoint.X) > SystemParameters.MinimumHorizontalDragDistance ||
                    Math.Abs(position.Y - _startPoint.Y) > SystemParameters.MinimumVerticalDragDistance)
                {
                    DependencyObject dep = (DependencyObject)e.OriginalSource;
                    while ((dep != null) && !(dep is DataGridRow) && !(dep is DataGridColumnHeader) && !(dep is Button)) // 同时排除表头和按钮上的拖动
                    {
                        // 检查是否是复选框或在复选框列内
                        if (dep is CheckBox cb && FindVisualParent<DataGridTemplateColumn>(cb)?.DisplayIndex == 0) // 假设复选框在第一列
                        {
                            // 如果是在复选框上开始拖动，可以允许
                            break; // 找到 CheckBox 或其容器，跳出循环
                        }
                        dep = VisualTreeHelper.GetParent(dep);
                    }

                    // 如果起始点不在行或第一列的复选框上，则不启动拖放
                    if (dep == null || (!(dep is DataGridRow) && !(dep is CheckBox))) // 必须在行内或复选框上
                    {
                        // Debug.WriteLine("MouseMove detected drag start outside a valid row/checkbox. Ignoring.");
                        return;
                    }

                    //    修改：不再直接使用 grid.SelectedItems   
                    if (sender is DataGrid grid && this.DataContext is SpaceManagerVm mainVm && mainVm.SpaceVM != null)
                    {
                        var spaceViewModel = mainVm.SpaceVM;
                        if (spaceViewModel.FilteredSpaceList != null)
                        {
                            //    核心修改：收集 IsSelected 为 true 的 ViewModel   
                            var selectedVMs = spaceViewModel.FilteredSpaceList
                                                .Where(vm => vm.IsSelected)
                                                .ToList();
                            // *************************************************

                            if (selectedVMs.Any()) // 只有当确实有通过复选框选中的项时才启动拖放
                            {
                                _isDragging = true; // 现在可以设置拖动状态
                                DataObject dragData = new DataObject("DraggedSpaceViewModels", selectedVMs);
                                Debug.WriteLine($"==> Starting DragDrop for {selectedVMs.Count} CHECKED spaces...");
                                DragDrop.DoDragDrop(grid, dragData, DragDropEffects.Move);
                                Debug.WriteLine($"==> DragDrop call completed.");
                                _isDragging = false; // 重置状态
                            }
                            else
                            {
                                Debug.WriteLine("No items selected via checkboxes to drag.");
                            }
                        }
                    }
                }
            }
            else if (e.LeftButton != MouseButtonState.Pressed)
            {
                _isDragging = false;
            }
        }
        // ---  NEW: SpaceType TreeView Drop Target Handlers  ---
        private void SpaceTypeTreeView_DragOver(object sender, DragEventArgs e)
        {
            try // 添加 try
            {
                e.Effects = DragDropEffects.None;
                if (e.Data.GetDataPresent("DraggedSpaceViewModels"))
                {
                    TreeViewItem targetItem = GetTreeViewItemUnderMouse(SpaceTypeTreeViewControl, e.GetPosition(SpaceTypeTreeViewControl));
                    Debug.WriteLine($"DragOver: Target TreeViewItem is null? {targetItem == null}"); // 添加日志
                    if (targetItem != null && targetItem.DataContext is SpaceTypeTreeNodeViewModel targetNode)
                    {
                        //   添加日志：打印目标节点信息    
                        Debug.WriteLine($"DragOver Node: '{targetNode.DisplayName}', IsLeaf: {targetNode.IsLeafNode}, TypeId: {targetNode.AssociatedSpaceTypeId}");
                        if (targetNode.IsLeafNode && targetNode.AssociatedSpaceTypeId != ElementId.InvalidElementId)
                        {
                            e.Effects = DragDropEffects.Move;
                        }
                    }
                }
            }
            catch (Exception ex) // 添加 catch
            {
                Debug.WriteLine($"!!!!!! EXCEPTION in SpaceTypeTreeView_DragOver: {ex.ToString()}");
            }
            e.Handled = true;
        }

        private void SpaceTypeTreeView_Drop(object sender, DragEventArgs e)
        {
            // 初始化变量
            SpaceTypeTreeNodeViewModel targetNode = null;
            List<SpaceDisplayViewModel> draggedSpaceVMs = null;

            try // 使用 try-finally 确保 e.Handled 总被设置
            {
                // 1. 检查拖放的数据格式是否正确
                if (e.Data.GetDataPresent("DraggedSpaceViewModels"))
                {
                    // 2. 获取拖动的数据 (空间 ViewModel 列表)
                    draggedSpaceVMs = e.Data.GetData("DraggedSpaceViewModels") as List<SpaceDisplayViewModel>;

                    // 3. 获取鼠标指针下的目标 TreeViewItem 和对应的 ViewModel
                    //    使用 SpaceTypeTreeViewControl 作为命中测试的控件
                    TreeViewItem targetItem = GetTreeViewItemUnderMouse(SpaceTypeTreeViewControl, e.GetPosition(SpaceTypeTreeViewControl));
                    targetNode = targetItem?.DataContext as SpaceTypeTreeNodeViewModel;

                    // 4. 检查是否成功获取了所有必要的信息
                    if (this.DataContext is SpaceManagerVm mainVm && // 获取主 ViewModel
                        mainVm.SpaceVM != null &&                   // 获取 SpaceTabViewModel
                        draggedSpaceVMs != null &&                  // 确保拖动数据有效
                        targetNode != null)                         // 确保目标节点有效
                    {
                        var spaceViewModel = mainVm.SpaceVM; // 获取 SpaceTabViewModel 实例

                        // 5. 验证目标节点是否是有效的放置目标
                        //    条件：必须是叶节点，并且已成功关联到 Revit SpaceType ID
                        if (targetNode.IsLeafNode && targetNode.AssociatedSpaceTypeId != ElementId.InvalidElementId)
                        {
                            // 6. 暂存目标节点和拖动的 ViewModel 列表到 SpaceTabViewModel
                            //    (假设 _dropTargetNode 和 _droppedSpaceVMs 在 SpaceTabViewModel 中是 public 或 internal 可访问的，
                            //     或者通过一个专门的方法来设置)
                            //    为了代码清晰，这里直接访问字段（需要调整访问修饰符或使用方法）

                            //  假设字段是 internal 或有 internal setter   
                            spaceViewModel._dropTargetNode = targetNode;
                            spaceViewModel._droppedSpaceVMs = draggedSpaceVMs;
                            // 触发新命令的 CanExecute 状态更新
                            (spaceViewModel.RequestConfirmAndAssignSpaceTypeCommand as RelayCommand)?.NotifyCanExecuteChanged();


                            Debug.WriteLine($"Drop: Stored target '{targetNode.DisplayName}' and {draggedSpaceVMs.Count} VMs for later confirmation.");

                            // 7. 使用 Dispatcher.BeginInvoke 异步调用新的确认和执行命令
                            //    这允许 Drop 事件快速完成，避免阻塞 UI，并可能解决时序问题
                            this.Dispatcher.BeginInvoke(new Action(() =>
                            {
                                try // 在 BeginInvoke 的 Action 中也添加 try-catch
                                {
                                    if (spaceViewModel.RequestConfirmAndAssignSpaceTypeCommand.CanExecute(null))
                                    {
                                        Debug.WriteLine("Drop -> BeginInvoke: Executing RequestConfirmAndAssignSpaceTypeCommand...");
                                        spaceViewModel.RequestConfirmAndAssignSpaceTypeCommand.Execute(null);
                                    }
                                    else
                                    {
                                        Debug.WriteLine("Drop -> BeginInvoke: RequestConfirmAndAssignSpaceTypeCommand cannot execute (target or VMs likely cleared or invalid).");
                                        // 如果命令不能执行，可能需要清理暂存状态
                                        spaceViewModel._dropTargetNode = null;
                                        spaceViewModel._droppedSpaceVMs = null;
                                        (spaceViewModel.RequestConfirmAndAssignSpaceTypeCommand as RelayCommand)?.NotifyCanExecuteChanged();
                                    }
                                }
                                catch (Exception ex)
                                {
                                    Debug.WriteLine($"!!!!!! EXCEPTION in Dispatcher.BeginInvoke Action for Drop: {ex.ToString()}");
                                    // 可以考虑在这里给用户一个提示
                                    MessageBox.Show($"执行拖放归类操作时发生内部错误: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                                    // 清理状态
                                    try
                                    {
                                        spaceViewModel._dropTargetNode = null;
                                        spaceViewModel._droppedSpaceVMs = null;
                                        (spaceViewModel.RequestConfirmAndAssignSpaceTypeCommand as RelayCommand)?.NotifyCanExecuteChanged();
                                    }
                                    catch { } // 忽略清理时的次要错误
                                }
                            }), System.Windows.Threading.DispatcherPriority.Background); // 使用较低优先级，给UI响应留出时间

                        }
                        else
                        {
                            Debug.WriteLine($"Drop: Target node '{targetNode.DisplayName}' is not a valid drop target (Not Leaf or Invalid TypeId).");
                            // 清理可能存在的旧暂存信息
                            spaceViewModel._dropTargetNode = null;
                            spaceViewModel._droppedSpaceVMs = null;
                            (spaceViewModel.RequestConfirmAndAssignSpaceTypeCommand as RelayCommand)?.NotifyCanExecuteChanged();
                        }
                    }
                    else
                    {
                        Debug.WriteLine("Drop Error: Failed to get ViewModels, dragged data, or target node.");
                    }
                }
                else
                {
                    Debug.WriteLine("Drop Error: Invalid data format ('DraggedSpaceViewModels' not present).");
                }
            }
            catch (Exception ex)
            {
                // 捕获 Drop 事件处理过程中的任何意外异常
                Debug.WriteLine($"!!!!!! FATAL EXCEPTION in SpaceTypeTreeView_Drop: {ex.ToString()}");
                MessageBox.Show($"处理拖放操作时发生严重错误: {ex.Message}", "严重错误", MessageBoxButton.OK, MessageBoxImage.Error);
                // 尝试清理状态
                try
                {
                    if (this.DataContext is SpaceManagerVm mainVm && mainVm.SpaceVM != null)
                    {
                        var spaceViewModel = mainVm.SpaceVM;
                        spaceViewModel._dropTargetNode = null;
                        spaceViewModel._droppedSpaceVMs = null;
                        (spaceViewModel.RequestConfirmAndAssignSpaceTypeCommand as RelayCommand)?.NotifyCanExecuteChanged();
                    }
                }
                catch { }
            }
            finally
            {
                // 确保事件被处理，并且可以在这里清除任何拖放过程中的视觉反馈（如果添加了的话）
                // 例如: ClearAllTreeViewItemHighlights(SpaceTypeTreeViewControl);
                e.Handled = true;
            }
        }
        // 用于清除高亮
        private void ClearAllTreeViewItemHighlights(ItemsControl itemsControl)
        {
            if (itemsControl == null) return;
            for (int i = 0; i < itemsControl.Items.Count; i++)
            {
                if (itemsControl.ItemContainerGenerator.ContainerFromIndex(i) is TreeViewItem tvi)
                {
                    tvi.Background = Brushes.Transparent; // Reset background
                    ClearAllTreeViewItemHighlights(tvi); // Recursively clear children
                }
            }
        }


        private void RootGrid_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            // 获取鼠标点击的原始源
            var originalSource = e.OriginalSource as DependencyObject;
            if (originalSource == null) return;

            // 检查点击的是否在 DataGrid 内部 (包括滚动条)
            var dataGrid = FindVisualParent<DataGrid>(originalSource);
            var scrollBar = FindVisualParent<ScrollBar>(originalSource); // 检查是否点击了滚动条

            // 如果点击的既不在 DataGrid 内，也不在滚动条上，则取消选中
            if (dataGrid == null && scrollBar == null)
            {
                // 取消 SpaceDataGrid 的选中
                if (SpaceDataGrid.SelectedItems.Count > 0)
                {
                    SpaceDataGrid.UnselectAll();
                    Debug.WriteLine("SpaceDataGrid selection cleared due to outside click.");
                }
                // 取消 RoomDataGrid 的选中 (如果房间视图也需要)
                if (RoomDataGrid.SelectedItems.Count > 0)
                {
                    RoomDataGrid.UnselectAll();
                    Debug.WriteLine("RoomDataGrid selection cleared due to outside click.");
                }
            }
            // 如果点击在 DataGrid 或 ScrollBar 内部，则不处理，让默认行为发生
        }

        // 辅助方法：查找可视化树上的父控件
        private static T FindVisualParent<T>(DependencyObject child) where T : DependencyObject
        {
            DependencyObject parentObject = VisualTreeHelper.GetParent(child);
            if (parentObject == null) return null;
            T parent = parentObject as T;
            if (parent != null)
                return parent;
            else
                return FindVisualParent<T>(parentObject);
        }



        private void HeaderCheckBox_Checked(object sender, RoutedEventArgs e)
        {
            // 获取 DataContext (SpaceTabViewModel)
            if (this.DataContext is SpaceManagerVm mainVm && mainVm.SpaceVM != null)
            {
                var spaceViewModel = mainVm.SpaceVM;
                if (spaceViewModel.FilteredSpaceList != null)
                {

                    foreach (var item in spaceViewModel.FilteredSpaceList)
                    {
                        item.IsSelected = true;
                    }

                }
            }
        }

        //  全选 CheckBox 取消选中事件 
        private void HeaderCheckBox_Unchecked(object sender, RoutedEventArgs e)
        {
            // 获取 DataContext (SpaceTabViewModel)
            if (this.DataContext is SpaceManagerVm mainVm && mainVm.SpaceVM != null)
            {
                var spaceViewModel = mainVm.SpaceVM;
                if (spaceViewModel.FilteredSpaceList != null)
                {
                    // 将所有项的 IsSelected 设置为 false
                    foreach (var item in spaceViewModel.FilteredSpaceList)
                    {
                        item.IsSelected = false;
                    }
                    // 可选：取消 DataGrid 的所有选中
                    // SpaceDataGrid.UnselectAll(); // 这也可能触发 SelectionChanged
                }
            }
        }



        /// <summary>
        /// 处理“空间类型”页面“列设置...”按钮的点击事件。
        /// </summary>
        private void HvacLoadColumnSettingsButton_Click(object sender, RoutedEventArgs e)
        {
            // 检查 ViewModel 是否有效
            if (_viewModel?.HAVCLoadVM == null)
            {
                MessageBox.Show(this, "无法访问空间类型视图模型。", "内部错误", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
            var hvacVm = _viewModel.HAVCLoadVM;

            // 1. 从 ViewModel 获取所有可用列信息
            var allAvailableColumns = hvacVm.AllAvailableColumns; // 假设这个是 internal 或 public 可访问

            // 2. 获取 DataGrid 当前各列的可见性状态
            var currentColumnInfos = new List<ColumnVisibilityInfo>();
            foreach (var column in SpaceTypeDataGrid.Columns) // 使用正确的 DataGrid Name
            {
                // 跳过复选框列 (通常是 DataGridTemplateColumn)
                if (column is DataGridTemplateColumn && column.HeaderTemplate != null) continue; // 简单判断

                // 尝试通过 Header 或 Binding Path 获取对应的属性名
                string propertyName = null;
                string header = column.Header?.ToString();

                if (column is DataGridBoundColumn boundCol && !string.IsNullOrEmpty(boundCol.SortMemberPath))
                {
                    propertyName = boundCol.SortMemberPath; // Binding Path 通常是属性名
                }
                else if (!string.IsNullOrEmpty(header))
                {
                    // 尝试通过 Header 从 allAvailableColumns 反查属性名 (作为后备)
                    var foundKvp = allAvailableColumns.FirstOrDefault(kvp => kvp.Value.Equals(header, StringComparison.Ordinal));
                    if (!foundKvp.Equals(default(KeyValuePair<string, string>)))
                    {
                        propertyName = foundKvp.Key;
                    }
                    else
                    {
                        propertyName = header; // 如果找不到，用 Header 作为标识符（不太可靠）
                    }
                }

                // 如果成功获取了标识符 (属性名或 Header)
                if (!string.IsNullOrEmpty(propertyName))
                {
                    // 从 allAvailableColumns 获取正确的显示名 (Header)
                    string displayHeader = header ?? (allAvailableColumns.TryGetValue(propertyName, out var foundHeader) ? foundHeader : propertyName);

                    currentColumnInfos.Add(new ColumnVisibilityInfo
                    {
                        Header = displayHeader,
                        ColumnName = propertyName, // 使用属性名作为唯一标识符
                        IsVisible = column.Visibility == System.Windows.Visibility.Visible
                    });
                }
                else
                {
                    Debug.WriteLine($"HvacLoadColumnSettingsButton_Click: 无法确定列 '{header ?? "未知列"}' 的属性名。");
                }
            }

            // 确保 currentColumnInfos 与 allAvailableColumns 同步 (处理可能的 DataGrid 列与 ViewModel 定义不一致)
            var finalColumnInfos = new List<ColumnVisibilityInfo>();
            foreach (var kvp in allAvailableColumns.OrderBy(kv => kv.Value)) // 以 ViewModel 定义为准
            {
                var existingInfo = currentColumnInfos.FirstOrDefault(ci => ci.ColumnName == kvp.Key);
                finalColumnInfos.Add(new ColumnVisibilityInfo
                {
                    Header = kvp.Value,
                    ColumnName = kvp.Key,
                    IsVisible = existingInfo?.IsVisible ?? false // 如果 DataGrid 中没有，则默认不可见
                });
            }


            // 3. 创建并显示对话框
            var dialog = new ColumnSelectionDialog(finalColumnInfos) { Owner = this };

            // 4. 处理对话框结果
            if (dialog.ShowDialog() == true)
            {
                var selectedInfos = dialog.ColumnInfos; // 获取用户修改后的列表
                foreach (var info in selectedInfos)
                {
                    // 根据 ColumnName (属性名) 找到对应的 DataGridColumn
                    DataGridColumn columnToUpdate = FindColumnByPropertyName(SpaceTypeDataGrid, info.ColumnName); // 使用新的查找方法
                    if (columnToUpdate != null)
                    {
                        // 更新 Visibility
                        columnToUpdate.Visibility = info.IsVisible ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
                    }
                    else
                    {
                        Debug.WriteLine($"HvacLoadColumnSettingsButton_Click: 未能在 DataGrid 中找到属性名为 '{info.ColumnName}' 的列。");
                    }
                }
                Debug.WriteLine("用户列设置已应用。");
                // 不再需要调用 SaveColumnPreferences
            }
            else
            {
                Debug.WriteLine("用户取消了列设置。");
            }
        }

        /// <summary>
        /// 处理“空间类型”页面 DataGrid 表头复选框的“选中”事件（全选）。
        /// </summary>
        private void HvacHeaderCheckBox_Checked(object sender, RoutedEventArgs e)
        {
            if (_viewModel?.HAVCLoadVM?.SpaceTypeList != null)
            {
                foreach (var item in _viewModel.HAVCLoadVM.SpaceTypeList) { item.IsSelected = true; }
            }
            (_viewModel?.HAVCLoadVM?.DeleteSpaceTypeCommand as AsyncRelayCommand)?.NotifyCanExecuteChanged();
        }

        /// <summary>
        /// 处理“空间类型”页面 DataGrid 表头复选框的“取消选中”事件（全不选）。
        /// </summary>
        private void HvacHeaderCheckBox_Unchecked(object sender, RoutedEventArgs e)
        {
            if (_viewModel?.HAVCLoadVM?.SpaceTypeList != null)
            {
                foreach (var item in _viewModel.HAVCLoadVM.SpaceTypeList) { item.IsSelected = false; }
            }
            (_viewModel?.HAVCLoadVM?.DeleteSpaceTypeCommand as AsyncRelayCommand)?.NotifyCanExecuteChanged();
        }

        // ****** 新增: 辅助方法，根据属性名查找列 ******
        private DataGridColumn FindColumnByPropertyName(DataGrid grid, string propertyName)
        {
            if (string.IsNullOrEmpty(propertyName) || grid == null) return null;
            foreach (var column in grid.Columns)
            {
                // 优先检查 DataGridBoundColumn 的 Binding Path (SortMemberPath 通常就是它)
                if (column is DataGridBoundColumn boundCol && boundCol.SortMemberPath == propertyName)
                {
                    return column;
                }
                // 可以添加对 DataGridTemplateColumn 的检查（如果模板列也需要控制）
                // 这需要更复杂的逻辑来检查模板内部元素的绑定路径，或者依赖 x:Name
                // if (column is DataGridTemplateColumn templateCol && ...) { ... }

                // 作为后备，检查列的 x:Name 是否匹配属性名 (如果在 XAML 中设置了 x:Name)
                if (column.GetValue(FrameworkElement.NameProperty)?.ToString() == $"HvacCol{propertyName}") // 假设 x:Name 遵循 HvacCol+属性名 的模式
                {
                    return column;
                }

            }
            Debug.WriteLine($"FindColumnByPropertyName: 未能找到属性名为 '{propertyName}' 的列。");
            return null;
        }

        private void SpaceTypeDataGrid_LoadingRow(object sender, DataGridRowEventArgs e)
        {
            // 当行加载时，获取对应的 ViewModel
            if (e.Row.DataContext is HVACLoadItemViewModel itemViewModel)
            {
                // 创建一个事件处理器
                PropertyChangedEventHandler handler = (s, args) =>
                {
                    // 只在 IsSelected 属性变化时触发
                    if (args.PropertyName == nameof(HVACLoadItemViewModel.IsSelected))
                    {
                        // 手动通知删除命令重新评估 CanExecute
                        // 使用 Dispatcher 确保在 UI 线程执行（虽然通常事件就在 UI 线程，但保险起见）
                        this.Dispatcher?.InvokeAsync(() =>
                        {
                            (_viewModel?.HAVCLoadVM?.DeleteSpaceTypeCommand as AsyncRelayCommand)?.NotifyCanExecuteChanged();
                        }, System.Windows.Threading.DispatcherPriority.DataBind); // 使用较低优先级
                    }
                };

                // 订阅属性变化事件
                itemViewModel.PropertyChanged += handler;
                // 存储处理器以便后续取消订阅
                _hvacItemPropertyChangedHandlers[itemViewModel] = handler;
            }
        }

        private void SpaceTypeDataGrid_UnloadingRow(object sender, DataGridRowEventArgs e)
        {
            // 当行卸载（例如，由于虚拟化或列表更新）时，取消订阅
            if (e.Row.DataContext is HVACLoadItemViewModel itemViewModel)
            {
                if (_hvacItemPropertyChangedHandlers.TryGetValue(itemViewModel, out var handler))
                {
                    itemViewModel.PropertyChanged -= handler; // 取消订阅
                    _hvacItemPropertyChangedHandlers.Remove(itemViewModel); // 从字典中移除
                }
            }
        }


    }
}